//
//  ActivitieDetailsViewController.m
//  TourPlay
//
//  Created by dllo on 15/11/19.
//  Copyright © 2015年 王军岐. All rights reserved.
//

#import "ActivitieDetailsViewController.h"
#import "ActivityDetailCell.h"
#import "AcitvityTimeCell.h"
#import "OrgNameCell.h"
#import "ActivityTextCell.h"
#import "AcitvityLikeCell.h"
#import "UMSocial.h"

#import "LikerListViewController.h" // 感兴趣的人子页面
#import "OriginViewController.h" // 发布人页面

@interface ActivitieDetailsViewController () <UIGestureRecognizerDelegate, UITableViewDataSource, UITableViewDelegate, UMSocialUIDelegate>

@property (nonatomic, retain) UITableView *activityTableV;
@property (nonatomic, retain) NSMutableArray *activityArr;


@property (nonatomic, retain) ActivityDetailCell *headCell;
@property (nonatomic, retain) AcitvityTimeCell *timeCell;
@property (nonatomic, retain) ActivityTextCell *textCell;
@property (nonatomic, retain) NSMutableDictionary *activityDic;
@property (nonatomic, retain) NSMutableArray *sortKeyArr;

@property (nonatomic, retain) MBProgressHUD *hub;

@property (nonatomic, copy) NSString *storeUpText;

@end

@implementation ActivitieDetailsViewController
- (void)dealloc
{
    [_hub release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"活动详情";
    
    NSLog(@"----%@", self.activityId);
    
    // 读取活动记录
    [self RecordActivity];
    // 读取收藏列表
    [self storeUpActivity];
    
    self.activityArr = [NSMutableArray arrayWithObjects:@"0", @"1", @"2", @"3", @"4", nil];
    self.activityDic = [NSMutableDictionary dictionary];
    self.sortKeyArr = [NSMutableArray array];
    
    
    
    // 右button
    UIImage *rightImage = [[UIImage imageNamed:@"icons_share_dark@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *rightLandscapeImage = [[UIImage imageNamed:@"icons_share_white@2x.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:rightImage landscapeImagePhone:rightLandscapeImage style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)] autorelease];
    
    
    self.activityTableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    self.activityTableV.delegate = self;
    self.activityTableV.dataSource = self;
    self.activityTableV.backgroundColor = [UIColor clearColor];
    self.activityTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.activityTableV registerClass:[ActivityDetailCell class] forCellReuseIdentifier:@"cell"];
    [self.activityTableV registerClass:[AcitvityTimeCell class] forCellReuseIdentifier:@"timeCell"];
    [self.activityTableV registerClass:[OrgNameCell class] forCellReuseIdentifier:@"orgCell"];
    [self.activityTableV registerClass:[AcitvityLikeCell class] forCellReuseIdentifier:@"likeCell"];
    [self.activityTableV registerClass:[ActivityTextCell class] forCellReuseIdentifier:@"textCell"];
    [self.view addSubview:self.activityTableV];
    [_activityTableV release];
    
    
    
    if (0 == self.activityId.length) {
        [self NetworkError:^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    } else {
        [self getUpdate];
    }
    [self addHeaderRefresh];
}
- (void)storeUpActivity
{
    NSMutableArray *select = [[Singleton shareSingleton] selectRecordActivityWithSQL:[NSString stringWithFormat:@"select * from storeUp where Id = '%@'", self.activityId]];
    
    if (0 != self.activityId.length) {
        
        if (0 == select.count) {
            self.storeUpText = @"收藏";
        } else {
            self.storeUpText = @"已收藏";
        }
    } else {
        self.storeUpText = @"error";
    }
    
    
}
- (void)RecordActivity
{
    NSMutableArray *select = [[Singleton shareSingleton] selectRecordActivityWithSQL:[NSString stringWithFormat:@"select * from Record where Id = '%@'", self.activityId]];
    
    if (0 == select.count && 0 != self.activityId.length) {
        
        [[Singleton shareSingleton] exeWithSQL:[NSString stringWithFormat:@"INSERT INTO Record(Id, time) VALUES('%@', '%@')", self.activityId, [AppTools getNowTime]]];
        
    }
    
}

-(void)addHeaderRefresh
{
    self.activityTableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [self getUpdate];
    }];
}
#pragma mark - 分享按钮
- (void)rightAction
{
    
    NSString *key = [self.activityDic.allKeys objectAtIndex:0];
    NSMutableArray *arr = [self.activityDic objectForKey:key];
    ActivityModel *activityMod = [arr objectAtIndex:0];
//    NSURL *url = [NSURL URLWithString:activityMod.pic];
//    [self.imageV sd_setImageWithURL:url placeholderImage:PICHOLDEER];
    NSLog(@"%@", activityMod.address);
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"正在测试"
                                     shareImage:nil
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToRenren,nil]
                                       delegate:self];
}


#pragma mark - 收藏相关
// 删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return YES;
    }
    return NO;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *select = [[Singleton shareSingleton] selectRecordActivityWithSQL:[NSString stringWithFormat:@"select * from storeUp where Id = '%@'", self.activityId]];
    
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        
        if (0 != select.count) {
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"已经收藏过了~";
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
            
        } else {
            
            [[Singleton shareSingleton] exeWithSQL:[NSString stringWithFormat:@"INSERT INTO storeUp(Id, time) VALUES('%@', '%@')", self.activityId, [AppTools getNowTime]]];
            self.storeUpText = @"已收藏";
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"收藏成功";
            hud.margin = 10.f;
            hud.removeFromSuperViewOnHide = YES;
            [hud hide:YES afterDelay:1];
            
        }
        
        [self.activityTableV reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.storeUpText;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.section) {
        return [self.headCell getCellHeight];
    } else if (1 == indexPath.section) {
        
        return [self.timeCell getCellHeight];
    } else if (2 == indexPath.section) {
        return 160.f;
    } else if (3 == indexPath.section) {
        return 50.f;
    }
    return [self.textCell getTextHeigth];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section) {
        return 0.f;
    }
    return 6.f;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSLog(@"%ld", self.sortKeyArr.count);
    return self.sortKeyArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [[self.activityDic objectForKey:[self.sortKeyArr objectAtIndex:section]] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    static NSString *timeCellStr = @"timeCell";
    static NSString *orgCellStr = @"orgCell";
    static NSString *textCellStr = @"textCell";
    static NSString *likeCellStr = @"likeCell";
    
    NSString *key = [self.activityDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.activityDic objectForKey:key];
    
    if (0 == indexPath.section) {

        self.headCell = [tableView dequeueReusableCellWithIdentifier:cellStr];
        [self.headCell setSelectionStyle:UITableViewCellSelectionStyleNone];

        self.headCell.activityMod = [arr objectAtIndex:indexPath.row];
        return _headCell;

        
    } else if (1 == indexPath.section) {
        
        self.timeCell = [tableView dequeueReusableCellWithIdentifier:timeCellStr];
        
        
        ActivityTimeMod *timeMod = [[self.activityDic objectForKey:@"1"] objectAtIndex:indexPath.row];
        [self.timeCell setIndexPath:indexPath timeMod:timeMod];
        
        // 只有显示地址的cell可以点击
        if (indexPath.row != 1) {
            [self.timeCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }

        
        
        self.timeCell.backgroundColor =  [UIColor clearColor];
        return _timeCell;
    } else if (2 == indexPath.section) {
        OrgNameCell *orgCell = [tableView dequeueReusableCellWithIdentifier:orgCellStr];

        ActivityModel *activityMod = [arr objectAtIndex:indexPath.row];
        if ([activityMod.orgname isEqualToString:@"大麦网"]) {
            [orgCell setSelectionStyle:UITableViewCellSelectionStyleNone];
            
        }
        orgCell.activityMod = activityMod;
        orgCell.backgroundColor = [UIColor clearColor];
        return orgCell;

    } else if (3 == indexPath.section) {
        
        AcitvityLikeCell *likeCell = [tableView dequeueReusableCellWithIdentifier:likeCellStr];
        likeCell.activityMod = [arr objectAtIndex:indexPath.row];
        likeCell.backgroundColor = [UIColor clearColor];
        return likeCell;
        
    } else {
        self.textCell = [tableView dequeueReusableCellWithIdentifier:textCellStr];
        self.textCell.activityMod = [arr objectAtIndex:indexPath.row];
        
        self.textCell.backgroundColor = [UIColor clearColor];
        [self.textCell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return _textCell;
    }

}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSString *key = [self.activityDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.activityDic objectForKey:key];
    ActivityModel *activityMod = [arr objectAtIndex:indexPath.row];


    if (3 == indexPath.section && 0 == indexPath.row) {
        LikerListViewController *likeVC = [[LikerListViewController alloc] init];
        
        likeVC.activityId = self.activityId;

        [self.navigationController pushViewController:likeVC animated:YES];
        [likeVC release];
    }
    if (2 == indexPath.section) {
        
        if (![activityMod.orgname isEqualToString:@"大麦网"]) {
            
            OriginViewController *originVC = [[OriginViewController alloc] init];
            originVC.orgId = activityMod.orgid;
            [self.navigationController pushViewController:originVC animated:YES];
            [originVC release];
        }
    }
    
}
#pragma mark - 获取数据
- (void)getUpdate
{
    
    // 让菊花旋转起来
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.hub show:YES];
    self.hub.labelText = @"努力加载中...";
    
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/proj.json?id=%@&source=%d&version=%d", self.activityId, URL_SOURCE, URL_VERSION];
    
    [AppTools getAFNet:url block:^(id result) {
        [self.activityDic removeAllObjects];
        [self.sortKeyArr removeAllObjects];
        
        NSMutableDictionary *bigDic = result;
        
        NSMutableDictionary *dic = [[bigDic objectForKey:@"data"] objectForKey:@"projinfo"];
        

        for (NSString *key in self.activityArr) {
            
            NSMutableArray *arr = [NSMutableArray array];
            if ([key isEqualToString:@"1"]) {
                
                ActivityTimeMod *timeMod = [ActivityTimeMod modelWithDictionary:dic];
                for (NSInteger i = 0; i < 3; i++) {
                    [arr addObject:timeMod];
                }
                
            } else {

                ActivityModel *activityMod = [ActivityModel modelWithDictionary:dic];
                activityMod.text = [[bigDic objectForKey:@"data"] objectForKey:@"text"];
                [arr addObject:activityMod];
                
            }
            [self.activityDic setObject:arr forKey:key];

        }
        
        self.sortKeyArr = [NSMutableArray arrayWithArray:self.activityDic.allKeys];
        [self.sortKeyArr sortUsingSelector:@selector(compare:)];
      
//        NSLog(@"%@", self.activityDic);
       
        
        
        [self.activityTableV reloadData];
        
        
        // 停止下拉刷新
        [self.activityTableV.header endRefreshing];
        // 让菊花停止旋转
        [self.hub hide:YES];
    } errorBlock:^(NSError *error) {
        [self NetworkError:^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        
        //结束下拉上拉刷新
        [self.activityTableV.header endRefreshing];
        [self.activityTableV.footer endRefreshing];
        [self.hub hide:YES];
    }];
}
/* 感兴趣的人
- (void)getUpdateLike
{
    NSString *url = [NSString stringWithFormat:@"http://wanapi.damai.cn/commodity/getlikerlist.json?cid=%@&pindex=0&psize=20&source=%d&version=%d", self.activityId, URL_SOURCE, URL_VERSION];
    
    [AppTools getAFNet:url block:^(id result) {
        
    } errorBlock:^(NSError *error) {
        NSLog(@"网络连接错误");
    }];

}
*/
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
